package cn.mvc.web.service;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.fast.ioc.annotation.Inject;
import org.fast.ioc.annotation.Service;
import org.fast.trans.Atom;
import org.fast.trans.Trans;
import org.fast.trans.exception.TransException;

import cn.mvc.common.SqlMapping;
import cn.mvc.exception.ServiceException;
import cn.mvc.model.Category;
import cn.mvc.web.dao.WebDao;

@Service("cateService")
public class CategoryService {

	@Inject
	private WebDao webDao;

	public WebDao getWebDao() {
		return webDao;
	}

	public void setWebDao(WebDao webDao) {
		this.webDao = webDao;
	}

	/**
	 * 添加分类
	 * 
	 * @param cate
	 * @return
	 * @throws ServiceException
	 */
	public int addCategory(Category cate) throws ServiceException {
		int r = 0;
		try {
			r = webDao.save("sql.category.update.add", cate, "name");
		} catch (SQLException e) {
			throw new ServiceException(e.getMessage());
		}
		return r;
	}

	public List<Category> queryCategories() throws ServiceException {
		List<Category> list = new ArrayList<Category>();
		try {
			list = webDao.list(Category.class, "sql.category.query.list");
		} catch (SQLException e) {
			throw new ServiceException(e.getMessage());
		}
		return list;
	}

	/**
	 * 删除分类 <br/>
	 * 删除分类时将分类下的内容移动到默认分类下<br/>
	 * 若移动失败则事务回滚.... 测试事务
	 * 
	 * @param id
	 * @return
	 * @throws ServiceException
	 */
	public int delCategory(final int id) throws ServiceException {
		final int[] r = new int[1];
		try {
			Trans.debug = true;
			Trans.exec(Connection.TRANSACTION_READ_COMMITTED, new Atom() {
				@Override
				public void run() {
					try {
						r[0] = webDao.update(SqlMapping.getSql("sql.category.update.del"), id);
						webDao.update(SqlMapping.getSql("sql.content.update.cate"), id);
					} catch (SQLException e) {
						throw new TransException(e);
					}

				}
			});
		} catch (TransException e) {
			throw new ServiceException(e.getMessage());
		}
		return r[0];
	}
}
